package com.tianshi.product.exceptionhandler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
* 自定义错误处理类，实现BlockExceptionHandler接口，用于处理sentinel限流异常
* 仅适用与controller层，不适用与service层
* */
@Component
@Slf4j
public class SentinelGlobalExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        String msg="未知异常";
        int status=429; //默认429状态码表示请求过快

        //判断异常类型
        if(e instanceof FlowException){
            // 限流异常
            msg="product请求过于频繁，请稍后再试";
        }

        //打印日志
        log.info(msg);


        //设置响应状态码和响应信息
        httpServletResponse.setContentType("application/json;charset=UTF-8"); //指定字符集
        httpServletResponse.setStatus(status); //设置响应状态码
        httpServletResponse.getWriter().write("{\"code\":\""+status+"\",\"msg\":\""+msg+"\"}"); //响应信息
    }
}
